import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    flowers: [], // 花卉列表
    cart: [], // 购物车
    user: null, // 用户信息
    categories: [], // 花卉分类
    // 模拟用户数据库
    users: [
      {
        username: "zy123",
        password: "123456",
        phone: "13800138000",
        email: "apq@example.com",
      },
    ],
  },
  getters: {
    cartTotal: (state) => {
      return state.cart.reduce(
        (total, item) => total + item.price * item.quantity,
        0
      );
    },
    cartCount: (state) => {
      return state.cart.reduce((count, item) => count + item.quantity, 0);
    },
  },
  mutations: {
    setFlowers(state, flowers) {
      state.flowers = flowers;
    },
    addToCart(state, flower) {
      const existingItem = state.cart.find((item) => item.id === flower.id);
      if (existingItem) {
        existingItem.quantity += flower.quantity || 1;
      } else {
        state.cart.push({ ...flower, quantity: flower.quantity || 1 });
      }
    },
    removeFromCart(state, item) {
      const index = state.cart.findIndex((cartItem) => cartItem.id === item.id);
      if (index > -1) {
        state.cart.splice(index, 1);
      }
    },
    setUser(state, user) {
      state.user = user;
      // 保存到本地存储
      if (user) {
        localStorage.setItem("user", JSON.stringify(user));
      } else {
        localStorage.removeItem("user");
      }
    },
    addUser(state, user) {
      state.users.push(user);
    },
    addToCartWithQuantity(state, { flower, quantity }) {
      const existingItem = state.cart.find((item) => item.id === flower.id);
      if (existingItem) {
        existingItem.quantity += quantity;
      } else {
        state.cart.push({ ...flower, quantity });
      }
    },
  },
  actions: {
    async fetchFlowers({ commit }) {
      const flowers = [
        {
          id: 1,
          name: "浪漫玫瑰花束",
          price: 299,
          image: require("@/assets/images/flower/photo-1561181286-d3fee7d55364.avif"),
          description: "精选19朵红玫瑰，完美诠释浪漫真爱",
          tags: ["热销", "七夕特惠"],
          stock: 100,
          categoryId: 1,
          sales: 200,
        },
        {
          id: 2,
          name: "向日葵花束",
          price: 199,
          image: require("@/assets/images/flower/photo-1563241527-3004b7be0ffd.avif"),
          description: "9朵向日葵，传递温暖阳光",
          tags: ["新品", "畅销"],
          stock: 50,
          categoryId: 3,
          sales: 150,
        },
        {
          id: 3,
          name: "混合花束",
          image: require("@/assets/images/flower/photo-1455582916367-25f75bfc6710.avif"),
          price: 399,
          description: "玫瑰+百合+康乃馨，精致混搭",
          tags: ["推荐", "节日优选"],
          stock: 30,
          categoryId: 3,
          sales: 180,
        },
        {
          id: 4,
          name: "永生花礼盒",
          price: 599,
          image: require("@/assets/images/flower/photo-1494336956603-39a3641efa1c.avif"),
          description: "永不凋谢的爱情见证",
          tags: ["高端", "永生花"],
          stock: 20,
          categoryId: 2,
          sales: 120,
        },
        {
          id: 5,
          name: "粉玫瑰花束",
          price: 289,
          image: require("@/assets/images/flower/photo-1525310072745-f49212b5ac6d.avif"),
          description: "19朵粉玫瑰，少女心满满",
          tags: ["热销", "生日推荐"],
          stock: 80,
          categoryId: 1,
          sales: 160,
        },
        {
          id: 6,
          name: "白色恋人",
          price: 359,
          image: require("@/assets/images/flower/photo-1582794543139-8ac9cb0f7b11.avif"),
          description: "纯洁白百合，高贵典雅",
          tags: ["新品", "婚礼推荐"],
          stock: 40,
          categoryId: 3,
          sales: 90,
        },
        {
          id: 7,
          name: "商务花篮",
          price: 699,
          image: require("@/assets/images/flower/photo-1591886960571-74d43a9d4166.avif"),
          description: "开业庆典，商务祝贺首选",
          tags: ["商务", "开业花篮"],
          stock: 15,
          categoryId: 5,
          sales: 50,
        },
        {
          id: 8,
          name: "甜心礼盒",
          price: 499,
          image: require("@/assets/images/flower/season_cover_tulip.jpg"),
          description: "玫瑰礼盒，送给心爱的她",
          tags: ["礼盒", "表白推荐"],
          stock: 25,
          categoryId: 4,
          sales: 140,
        },
      ];
      commit("setFlowers", flowers);
    },
    async login({ commit, state }, credentials) {
      // 模拟API延迟
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 查找用户
      const user = state.users.find(
        (u) =>
          (u.username === credentials.username ||
            u.phone === credentials.username) &&
          u.password === credentials.password
      );

      if (user) {
        // 移除密码等敏感信息
        const { password, ...safeUser } = user;
        commit("setUser", safeUser);
        return Promise.resolve(safeUser);
      } else {
        return Promise.reject(new Error("用户名或密码错误"));
      }
    },
    async register({ commit, state }, userData) {
      // 模拟API延迟
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 检查用户名是否已存在
      if (state.users.some((u) => u.username === userData.username)) {
        return Promise.reject(new Error("用户名已存在"));
      }

      // 检查手机号是否已存在
      if (state.users.some((u) => u.phone === userData.phone)) {
        return Promise.reject(new Error("手机号已被注册"));
      }

      // 添加新用户
      const newUser = {
        username: userData.username,
        password: userData.password,
        phone: userData.phone,
        createdAt: new Date().toISOString(),
      };

      commit("addUser", newUser);
      return Promise.resolve();
    },
    logout({ commit }) {
      commit("setUser", null);
    },
    // 检查本地存储中的用户信息
    checkAuth({ commit }) {
      const userStr = localStorage.getItem("user");
      if (userStr) {
        try {
          const user = JSON.parse(userStr);
          commit("setUser", user);
        } catch (e) {
          localStorage.removeItem("user");
        }
      }
    },
  },
});
